<%@ page import="com.cinsea.form.model.Formrelationship" %>
<%@ page import="com.cinsea.schedule.model.Schedulesetting" %>
<%@ page import="com.cinsea.form.model.Formfield" %>
<%@ page import="com.cinsea.workflow.service.WfdefineService" %>
<%@ page import="com.cinsea.workflow.model.Wfdefine" %>
<%@ page import="com.cinsea.schedule.service.SchedulesettingService" %>
<%@ page import="com.cinsea.workflow.service.WfnodeService" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ include file="/common/common.jsp" %>
<%

    String startdate0 = StringUtil.null2String(request.getParameter("startdate"));
    WfdefineService wfdefineService = (WfdefineService) Env.getBean("wfdefineService");
    DirectoryService directoryService = (DirectoryService) Env.getBean("directoryService");
    FormService formService = (FormService) Env.getBean("formService");
    FormrelationshipService formrelationshipService = (FormrelationshipService) Env.getBean("formrelationshipService");
    SchedulesettingService schedulesettingService = (SchedulesettingService) Env.getBean("schedulesettingService");
    FormfieldService formfieldService = (FormfieldService) Env.getBean("formfieldService");
    JdbcDao jdbcDao = (JdbcDao) Env.getBean("jdbcDao");
    BrowserService browserService = (BrowserService) Env.getBean("browserService");
    if (StringUtil.isEmpty(startdate0)) {
        startdate0 = DateUtil.getCurrentMonth() + "-01";
    }
    String enddate0 = StringUtil.null2String(request.getParameter("enddate"));
    if (StringUtil.isEmpty(enddate0)) {
        enddate0 = DateUtil.getLastDayOfMonth(DateUtil.getCurrentDate());
    }
    String formid = "";
    String directoryid = StringUtil.null2String(request.getParameter("directoryid"));
    String workflowid = StringUtil.null2String(request.getParameter("workflowid"));
    if (StringUtil.isEmpty(directoryid)) {
        Wfdefine wf = wfdefineService.get(workflowid);
        formid = wf.getFormid();
    } else {
        Directory directory = directoryService.getDirectoryById(directoryid);
        formid = directory.getPFormid();
    }
    Form form = formService.getFormById(formid);
    int formtype = form.getObjtype().intValue();
    String hsql;

        String formids = formid;
        String strHql = "from Formrelationship where hostid='" + formid + "' order by slaveid";
        List list = formrelationshipService.findFormlink(strHql);
        for (int i = 0; i < list.size(); i++) {
            Formrelationship formlink = (Formrelationship) list.get(i);
            String pid = formlink.getSlaveid();
            if (formids.equals(""))
                formids += pid;
            else
                formids += "','" + pid;
        }
        hsql = "from Schedulesetting where formid in('" + formids + "')";

     list = schedulesettingService.find(hsql);
    Schedulesetting schedulesetting = new Schedulesetting();
    for (int i = 0; i < list.size(); i++) {
        schedulesetting = (Schedulesetting) list.get(0);//不管scheduleset有没有多个 暂且考虑第一个
        form = formService.getFormById(schedulesetting.getFormid());
        break;
    }
    String resources = "";
    String begindate = "";
    String enddate = "";
    String title = "";
    String color = "";
    String begintime = "";
    String endtime = "";
    if (!StringUtil.isEmpty(schedulesetting.getId())) {
        resources = StringUtil.null2String(formfieldService.getFormfieldById(schedulesetting.getResourcefield()).getFieldname()).toLowerCase();
        begindate = StringUtil.null2String(formfieldService.getFormfieldById(schedulesetting.getBegindatefield()).getFieldname()).toLowerCase();
        enddate = StringUtil.null2String(formfieldService.getFormfieldById(schedulesetting.getEnddatefield()).getFieldname()).toLowerCase();
        begintime = StringUtil.null2String(formfieldService.getFormfieldById(schedulesetting.getBegintimefield()).getFieldname()).toLowerCase();
        endtime = StringUtil.null2String(formfieldService.getFormfieldById(schedulesetting.getEndtimefield()).getFieldname()).toLowerCase();
        color = StringUtil.null2String(formfieldService.getFormfieldById(schedulesetting.getColorfield()).getFieldname()).toLowerCase();
        title = StringUtil.null2String(formfieldService.getFormfieldById(schedulesetting.getTitlefield()).getFieldname()).toLowerCase();
    } else {
        resources = "resource";
        begindate = "begindate";
        enddate = "enddate";
        title = "title";
        color = "color";
        begintime = "begintime";
        endtime = "endtime";
    }
    Formfield formfield = formfieldService.getFormfieldById(schedulesetting.getResourcefield());
    //Browser browser = browserService.get(formfield.getDatatype());
    resources="taskname";
    String sql = "select processid,taskname from ut_prjtask where deleted=0";
    String sql1 = "select * from " + form.getTablename() + " where " + begindate + " <= ? and " + enddate + ">=? order by "+begintime;      //range:start
    String sql2 = "select * from " + form.getTablename() + " where " + begindate + " <= ? and " + enddate + ">=? order by "+begintime;      //range:end
    String sql3 = "select * from " + form.getTablename() + " where " + begindate + " >= ? and " + enddate + "<=? order by "+begintime;      //range:end
    List<Map> list1 = jdbcDao.getJdbcTemplate().queryForList(sql1.toLowerCase(), new Object[]{startdate0, startdate0});
    List<Map> list2 = jdbcDao.getJdbcTemplate().queryForList(sql2.toLowerCase(), new Object[]{enddate0, enddate0});
    List<Map> list3 = jdbcDao.getJdbcTemplate().queryForList(sql3.toLowerCase(), new Object[]{startdate0, enddate0});
    List<Map> resourcelist = jdbcDao.queryForList(sql);
    List array = new ArrayList();
    Set<String> ids1=new HashSet();
    for (Map resource : resourcelist) {
        String resourceid = ((Map) resource).get("taskname").toString();
        String resourcename = ((Map) resource).get("taskname").toString();
        boolean existed = false;
        for (Object o : list1) {
            List object = new ArrayList();
            String processid = ((Map) o).get("processid") == null ? "" : ((Map) o).get("processid").toString();
            String resourcesid = ((Map) o).get(resources) == null ? "" : ((Map) o).get(resources).toString();
            ids1.add(processid);
            if (resourcesid.equals(resourceid)) {
                existed = true;
                object.add(resourceid);
                //object.put("processid", processid);
                object.add(resourcename);
                String title1 = ((Map) o).get(title) == null ? "" : ((Map) o).get(title).toString();
                String BeginDate = ((Map) o).get(begindate) == null ? "" : ((Map) o).get(begindate).toString();
                String begintime1 = ((Map) o).get(begintime) == null ? "00:00:00" : ((Map) o).get(begintime).toString();
                String enddate1 = ((Map) o).get(enddate) == null ? "" : ((Map) o).get(enddate).toString();
                String endtime1 = ((Map) o).get(endtime) == null ? "23:59:59" : ((Map) o).get(endtime).toString();
                if(begintime1.equals(endtime1)) endtime1="23:59:59";
                object.add(title1+"("+BeginDate + " " + begintime1+"至"+enddate1+" "+endtime1+")");
                String begin = DateUtil.formatDatetime(BeginDate + " " + begintime1, "M/d/yyyy H:m:s");
                object.add(DateUtil.formatDatetime(startdate0 + " 00:00:00", "M/d/yyyy H:m:s"));
                String end = DateUtil.formatDatetime(enddate1 + " " + endtime1, "M/d/yyyy H:m:s");
                object.add(end);
                object.add("0");
                String color1 = ((Map) o).get(color) == null ? "" : ((Map) o).get(color).toString();
                if (StringUtil.isEmpty(color1)) {
                    Integer finished = ((Map) o).get("finished") == null ? -1 : (Integer) ((Map) o).get("finished");
                    if (finished == 1) color1 = "red";
                    if (finished == 0) color1 = "yellow";
                    if (finished == -1) color1 = "red";
                    object.add(color1);
                } else {
                    Option selectitemcolor = optionService.get(color1);
                    object.add(selectitemcolor.getObjdesc());
                }
                object.add(processid);
                array.add(object);
            }
        }
        Set<String> ids2=new HashSet();
        for (Object o : list2) {
            List object = new ArrayList();
            String processid = ((Map) o).get("processid") == null ? "" : ((Map) o).get("processid").toString();
            String resourcesid = ((Map) o).get(resources) == null ? "" : ((Map) o).get(resources).toString();
            if(ids1.contains(processid)) continue;
            else ids2.add(processid);
            if (resourcesid.equals(resourceid)) {
                existed = true;
                object.add(resourceid);
                //object.add(processid);
                object.add(resourcename);
                String title1 = ((Map) o).get(title) == null ? "" : ((Map) o).get(title).toString();
                String BeginDate = ((Map) o).get(begindate) == null ? "" : ((Map) o).get(begindate).toString();
                String begintime1 = ((Map) o).get(begintime) == null ? "00:00:00" : ((Map) o).get(begintime).toString();
                String enddate1 = ((Map) o).get(enddate) == null ? "" : ((Map) o).get(enddate).toString();
                String endtime1 = ((Map) o).get(endtime) == null ? "23:59:59" : ((Map) o).get(endtime).toString();
                if(begintime1.equals(endtime1)) endtime1="23:59:59";
                String begin = DateUtil.formatDatetime(BeginDate + " " + begintime1, "M/d/yyyy H:m:s");
                object.add(title1+"("+BeginDate + " " + begintime1+"至"+enddate1+" "+endtime1+")");
                object.add(begin);
                String end = DateUtil.formatDatetime(enddate1 + " " + endtime1, "M/d/yyyy H:m:s");
                object.add(DateUtil.formatDatetime(enddate0 + " 23:59:59", "M/d/yyyy H:m:s"));
                object.add("0");
                String color1 = ((Map) o).get(color) == null ? "" : ((Map) o).get(color).toString();
                if (StringUtil.isEmpty(color1)) {
                    Integer finished = ((Map) o).get("finished") == null ? -1 : (Integer) ((Map) o).get("finished");
                    if (finished == 1) color1 = "red";
                    if (finished == 0) color1 = "yellow";
                    if (finished == -1) color1 = "red";
                    object.add(color1);
                } else {
                    Option selectitemcolor = optionService.get(color1);
                    object.add(selectitemcolor.getObjdesc());
                }
                object.add(processid);
                array.add(object);
            }
        }
        for (Object o : list3) {
            List object = new ArrayList();
            String processid = ((Map) o).get("processid") == null ? "" : ((Map) o).get("processid").toString();
            String resourcesid = ((Map) o).get(resources) == null ? "" : ((Map) o).get(resources).toString();
            if(ids1.contains(processid)||ids2.contains(processid)) continue;
            if (resourcesid.equals(resourceid)) {
                existed = true;
                object.add(resourceid);
                //object.add(processid);
                object.add(resourcename);
                String title1 = ((Map) o).get(title) == null ? "" : ((Map) o).get(title).toString();
                String BeginDate = ((Map) o).get(begindate) == null ? "" : ((Map) o).get(begindate).toString();
                String begintime1 = ((Map) o).get(begintime) == null ? "00:00:00" : ((Map) o).get(begintime).toString();
                String enddate1 = ((Map) o).get(enddate) == null ? "" : ((Map) o).get(enddate).toString();
                String endtime1 = ((Map) o).get(endtime) == null ? "23:59:59" : ((Map) o).get(endtime).toString();
                if(begintime1.equals(endtime1)) endtime1="23:59:59";
                String begin = DateUtil.formatDatetime(BeginDate + " " + begintime1, "M/d/yyyy H:m:s");
                object.add(title1+"("+BeginDate + " " + begintime1+"至"+enddate1+" "+endtime1+")");
                object.add(begin);
                String end = DateUtil.formatDatetime(enddate1 + " " + endtime1, "M/d/yyyy H:m:s");
                object.add(end);
                object.add("0");
                String color1 = ((Map) o).get(color) == null ? "" : ((Map) o).get(color).toString();
                if (StringUtil.isEmpty(color1)) {
                    Integer finished = ((Map) o).get("finished") == null ? -1 : (Integer) ((Map) o).get("finished");
                    if (finished == 1) color1 = "red";
                    if (finished == 0) color1 = "yellow";
                    if (finished == -1) color1 = "red";
                    object.add(color1);
                } else {
                    Option selectitemcolor = optionService.get(color1);
                    object.add(selectitemcolor.getObjdesc());
                }
                object.add(processid);
                array.add(object);
            }
        }
        if (!existed) {
            List object = new ArrayList();
            object.add(resourceid);
            object.add(resourcename);
            object.add("");
            object.add("");
            object.add("");
            object.add("0");
            object.add("");
            object.add("");
            array.add(object);
        }

    }

    pagemenustr += "addBtn(tb,'" + I18n.getText("search") + "','S','zoom',function(){onsearch()});";
%>
<html>
<head>
    <%@ include file="/common/head.jsp" %>
    <link rel="stylesheet" type="text/css" href="${ctx}/js/ext/ux/css/Ext.ux.Schedule.css"/>
    <script type="text/javascript" src="${ctx}/js/ext/ux/Ext.ux.ScheduleModel.js"></script>
    <script type="text/javascript" src="${ctx}/js/ext/ux/Ext.ux.TimelineModel.js"></script>
    <script type="text/javascript" src="${ctx}/js/ext/ux/Ext.ux.ScheduleView.js"></script>
    <script type="text/javascript" src="${ctx}/js/ext/ux/Ext.ux.SchedulePanel.js"></script>
    <script type="text/javascript" src="${ctx}/js/ext/ux/Ext.ux.AbstractScheduleSelectionModel.js"></script>
    <script type="text/javascript" src="${ctx}/js/ext/ux/Ext.ux.ScheduleRowSelectionModel.js"></script>
    <script type="text/javascript">
        Ext.onReady(function() {
            Ext.QuickTips.init();
            <%if(!pagemenustr.equals("")){%>
            var tb = new Ext.Toolbar();
            tb.render('pagemenubar');
            <%=pagemenustr%>
            <%}%>
            var scheduleStore = new Ext.data.SimpleStore({
                id:'id',
                data:<%=JSON.toJSONString(array)%> ,
                fields:['id', 'resources', 'subject', 'startdate', 'enddate', 'parent', 'color','processid']
            });

            /*var scheduleStore = new Ext.data.JsonStore({
             id:'id',
             url: '
            ${ctx}/schedule.do?action=gettimeline',
             root:'result',
             fields:['id', 'resources', 'subject', 'startdate', 'enddate', 'parent', 'color']
             });
             scheduleStore.load({params:{startdate:'
            <%=startdate0%>', enddate:'
            <%=enddate0%>',workflowid:'4028ed812d03d6ac012d03daac9d0019'}}) ;*/
            //setup a timeline Model
            var timelineModel = new Ext.ux.TimelineModel([
                {
                    timeUnit: 'MINUTE',
                    interval: 1440,
                    renderer: function(date) {
                        return date.format('d')
                    },
                    stagger: false,
                    width:30
                }
            ]);
            var scheduleModel = new Ext.ux.ScheduleModel({
                title: '资源(<span style=background-color:red>已占用</span><span style=background-color:yellow>申请中</span>) ',
                titleRenderer: null, //Title can be rendered as plain text
                labelDataIndex: 'resources',
                labelRenderer: null,
                labelWidth: 220,
                labelAlign: 'left',
                activityDataIndex: 'subject',
                activityRenderer: activityRenderer,
                idIndex: 'id',
                startDateIndex: 'startdate',
                endDateIndex: 'enddate',
                parentDataIndex: 'parent',
                colorDataIndex: 'color',
                startDate: '<%=DateUtil.formatDate(startdate0,"M/d/yyyy")%>',
                endDate:'<%=DateUtil.formatDate(enddate0,"M/d/yyyy")%>'
            });
            function activityRenderer(v,r,j){
                return '';// '<font style="width:100%" ext:qtip="'+v+'" onclick="alert(\''+ r.get('processid')+'\')"></font>';
            }
            //create a new schedule panel
            var schedule = new Ext.ux.SchedulePanel({
                store: scheduleStore,
                timelineModel: timelineModel,
                scheduleModel: scheduleModel,
                selModel: new Ext.ux.ScheduleRowSelectionModel({singleSelect:true}),
                frame:true,
                region: 'center'
            });

//Viewport
            var viewport = new Ext.Viewport({
                layout: 'border',
                items: [
                    {region:'north',width:30,autoScroll:true,contentEl:'divSearch',split:true,collapseMode:'mini'},
                    schedule
                ]
            });

        });
    </script>
</head>
<body>
<div id="divSearch">
    <div id="pagemenubar"></div>
    <form name="mainForm" id="mainForm" method="post">
        <table id=searchTable>
            <colgroup>
                <col width="10%">
                <col width="15%">
                <col width="10%">
                <col width="15%">
            </colgroup>

            <tr>
                <td class="FieldName" width=10% nowrap>
                    开始日期
                </td>
                <td class="FieldValue">
                    <input type=text class=inputstyle size=10 name="startdate"
                           value="<%=StringUtil.null2String(startdate0)%>" onclick="WdatePicker()">
                </td>
                <td class="FieldName" width=10% nowrap>
                    结束日期
                </td>
                <td class="FieldValue">
                    <input type=text class=inputstyle size=10 name="enddate"
                           value="<%=StringUtil.null2String(enddate0)%>" onclick="WdatePicker()">
                </td>

            </tr>

        </table>
    </form>
</div>
<script>
    function onsearch() {
        document.getElementById('mainForm').submit();

    }
    $(document).keydown(function(event) {
        if (event.keyCode == 13) {
            onsearch();
        }
    });
</script>
<script type="text/javascript" language="javascript"
        src="<%= request.getContextPath()%>/datapicker/WdatePicker.js"></script>
</body>
</html>
